#!/usr/bin/env node
var fs = require("fs");
function btoa(str) { return new Buffer.from(str).toString('base64'); }
function atob(str) { return new Buffer.from(str, 'base64').toString(); }
try {
	fs.accessSync('data.json', fs.constants.R_OK | fs.constants.W_OK);
	// console.log('OK');
	var json = JSON.parse(fs.readFileSync('data.json'));
	for (var i = 0; i < json.length; i++) {
		if ('lnk' in json[i]) {
			if (typeof json[i]['lnk'] == 'object') {
				json[i]['dat'] = [];
				json[i]['lnk'].forEach((val, ind, arr) => {
					json[i]['dat'][ind] = btoa(val);
				});
			} else {
				json[i]['dat'] = btoa(json[i]['lnk']); // data
			}
			delete json[i]['lnk']; // link
		}
	}
	fs.writeFileSync('data.json', JSON.stringify(json, null, '\t'));
	fs.writeFileSync('data.html', '<html>\n\t<head>\n\t\t<meta charset="utf-8">\n\t' + ((process.argv.length > 2) ? ('\t<link rel="stylesheet" type="text/css" href="' + process.argv[2] + '">\n') : '') + '\t</head>\n\t<body>\n\t\t<script>\n\t\t\tfunction d2l(d) {\n\t\t\t\tl = window.atob(d);\n\t\t\t\tif (window.confirm("获得链接：" + l + "\\n是否现在前往？")) {\n\t\t\t\t\tr = window.open(l);\n\t\t\t\t\tif (r == null || typeof(r) == "undefined") {\n\t\t\t\t\t\twindow.alert("窗口打开失败，尝试手动打开。");\n\t\t\t\t\t\tdocument.write(\'<a href="\' + l +\'" target="_blank">手动打开</a>\');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t</script>' + (function(){ var res=""; for(var j of json){ res+='\n\t\t<p>'+((typeof j['dat'] === 'object')?((function(){var s=j['name'];for(var k=0;k<j['dat'].length;k++){ s+=' <a href="#" onclick="d2l(\''+j['dat'][k]+'\')">地址'+(k+1).toString()+'</a>'; } return s;})()):('<a href="#" onclick="d2l(\''+j['dat']+'\')">'+j['name']+'</a>'))+'</p>'; } return res; })() + '\n\t</body>\n</html>');
} catch (err) {
	// console.log('cannot read/write to data.json')
	console.log('An error occurred. Error message:\n' + err);
	process.exit(1);
}
